package com.memory.admin.earn.controller;

import com.memory.common.exception.ResultException;
import com.memory.common.utils.ResultVoUtil;
import com.memory.common.vo.ResultVo;
import com.memory.component.actionLog.annotation.EntityParam;
import com.memory.modules.business.domain.earn.AccountEarn;
import com.memory.modules.business.service.earn.AccountEarnService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @PackageName: com.memory.admin.earn.controller
 * @ClassName: AccountEarnController
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/13
 */
@Controller
@RequestMapping("/business/account/earn")
@RequiredArgsConstructor
public class AccountEarnController {

    private final static String path = "/business/accountearn/";

    private final AccountEarnService accountEarnService;

    @GetMapping("list")
    public String list(AccountEarn accountEarn, Model model) {
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<AccountEarn> example = Example.of(accountEarn, matcher);
        final Page<AccountEarn> page = accountEarnService.findPage(example);
        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return path + "list";
    }

    @GetMapping("add")
    public String add() {
        return path + "add";
    }

    @GetMapping("edit/{id}")
    public String modify(@PathVariable("id") Long id, Model model) {
        final Optional<AccountEarn> byId = accountEarnService.findById(id);
        model.addAttribute("accountEarn", byId.orElseThrow(() -> new ResultException(500, "未获取记录")));
        return path + "add";
    }

    @PostMapping("save")
    public @ResponseBody
    ResultVo save(@EntityParam AccountEarn accountEarn) {
        if (accountEarn.getId() != null) {
            accountEarnService.modify(accountEarn.getId(), accountEarn);
        } else {
            accountEarnService.create(accountEarn);
        }
        return ResultVoUtil.SAVE_SUCCESS;
    }

    @GetMapping("remove/{id}")
    public ResultVo remove(@PathVariable Long id) {
        accountEarnService.remove(id);
        return ResultVoUtil.SAVE_SUCCESS;
    }
}
